#include "fwTexture.h"

Texture::Texture()
{

}

Texture::~Texture()
{

}

FWint Texture::Init(FWuint count, char** value)
{
	TBOCount = count;
	TBOs = new FWuint[TBOCount];
	glGenTextures(TBOCount, TBOs);

	FWint iWidth, iHeight, iBPP;
	char* src = NULL;
	FWint formatType;

	for (FWuint i = 0; i < TBOCount; i++)
	{
		src = TGAImage::LoadTGA(value[i], &iWidth, &iHeight, &iBPP);
		switch (iBPP)
		{
		case 24:
			formatType = GL_RGB;
			break;
		case 32:
			formatType = GL_RGBA;
			break;
		default:
			SAFE_DEL_ARRAY(src);
			glDeleteTextures(TBOCount, TBOs);
			SAFE_DEL_ARRAY(TBOs);
			return -1;
		};

		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, TBOs[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, formatType, iWidth, iHeight, 0, formatType, GL_UNSIGNED_BYTE, src);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glGenerateMipmap(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, 0);

		SAFE_DEL_ARRAY(src);
	}
	return 0;
}

FWint Texture::Init(FWuint count, char** value, FWuint type)
{
	switch (type)
	{
	case GL_TEXTURE_2D:
		return Init(count, value);
	case GL_TEXTURE_CUBE_MAP:
		break;
	default:
		return -1;
	}

	TBOCount = 1;
	TBOs = new FWuint[TBOCount];
	glGenTextures(1, TBOs);

	FWint iWidth, iHeight, iBPP;
	char* src = NULL;
	FWint formatType;

	glBindTexture(GL_TEXTURE_CUBE_MAP, TBOs[0]);
	for (FWuint i = 0; i < count; i++)
	{
		src = TGAImage::LoadTGA(value[i], &iWidth, &iHeight, &iBPP);
		switch (iBPP)
		{
		case 24:
			formatType = GL_RGB;
			break;
		case 32:
			formatType = GL_RGBA;
			break;
		default:
			SAFE_DEL_ARRAY(src);
			glDeleteTextures(TBOCount, TBOs);
			SAFE_DEL_ARRAY(TBOs);
			return -1;
		};
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, formatType, iWidth, iHeight, 0, formatType, GL_UNSIGNED_BYTE, src);
		SAFE_DEL_ARRAY(src);
	}

	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

	return 0;
}

void Texture::Destroy()
{
	glDeleteTextures(TBOCount, TBOs);
	SAFE_DEL_ARRAY(TBOs);
}